package com.heima.admin.service.Impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.UserService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.MD5Utils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author shiminghui
 * @date 2024/12/17 21:02
 * @description: TODO
 */
@Service
public class UserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements UserService {
    @Autowired
    private AdUserMapper adUserMapper;

    /**
     * 用户登录
     *
     * @param adUserDto
     * @return
     */
    @Override
    public ResponseResult login(AdUserDto adUserDto) {

        // 校验用户名密码
        if (adUserDto == null || StringUtils.isBlank(adUserDto.getName()) || StringUtils.isBlank(adUserDto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 查询用户是否存在
        AdUser adUser = adUserMapper.selectOne(Wrappers.lambdaQuery(AdUser.class).eq(AdUser::getName, adUserDto.getName()));
        if (adUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 密码加密
        String registerPassword = DigestUtils.md5DigestAsHex((adUserDto.getPassword() + adUser.getSalt()).getBytes(StandardCharsets.UTF_8));

        if (!registerPassword.equals(adUser.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        // 生成 jwt
        Map<String, Object> map = new HashMap<>();
        map.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
        adUser.setSalt("");
        adUser.setPassword("");
        map.put("user", adUser);
        return ResponseResult.okResult(map);
    }
}
